<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 头部 -->
        <tree-tool :tree="company" :is-root="true" style="height:30px" @addDep="addDep" />
        <!-- 组织结构树 -->
        <el-tree :data="departs" :props="defaultProps">
          <template v-slot="{data}">
            <tree-tool :tree="data" @updateDeps="getgetDepartments" @addDep="addDep" @editDep="editDepFn" />
          </template>
        </el-tree>
      </el-card>
      <AddDep
        ref="addDep"
        :visible.sync="addVisible"
        :current-node="currentNode"
        :origin-depts="originDepts"
        @updateDeps="getgetDepartments"
      />
    </div>
  </div>
</template>
<script>
import TreeTool from '@/views/departments/components/TreeTool.vue'
import { getDepartments } from '@/api/department'
import { createTree } from '@/utils'
import AddDep from '@/views/departments/components/AddDep.vue'
export default {
  components: { TreeTool, AddDep },
  data() {
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      company: {},
      departs: [],
      addVisible: false,
      currentNode: {},
      originDepts: [],
      loading: false
    }
  },

  created() {
    this.getgetDepartments()
  },

  methods: {
    async getgetDepartments() {
      try {
        this.loading = true
        const res = await getDepartments()
        this.originDepts = res.depts
        this.departs = createTree(res.depts, '')
        this.company = { name: res.companyName,
          manager: '负责人',
          children: this.departs }
      } finally {
        this.loading = false
      }
    },
    addDep(currentNode) {
      console.log('添加部门')
      this.addVisible = true
      this.currentNode = currentNode
    },
    editDepFn(currentNode) {
      this.addVisible = true
      this.$refs.addDep.formData = { ...currentNode }
    }
  }

}
</script>

<style scoped>
.tree-card {
  padding: 30px  60px;
  font-size:14px;
}
</style>
